from flask import Flask
from flask_jwt_extended import JWTManager
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager


# 设置数据库连接字符串
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:lql19951126..@114.55.93.211/school4?charset=UTF8MB4'
# 不跟踪修改，不设置会有警告
SQLALCHEMY_TRACK_MODIFICATIONS = False
# 设置csrf_key
SECRET_KEY = 'asda564654adaasd24654asda'
# 设置每页显示条数
COUNT_PER_PAGE = 10

# 初始化LoginManager
login_manager = LoginManager()
# 登录会话的安全检查，级别设为最高
login_manager.session_protection = 'strong'
# 设置login的视图函数地址
login_manager.login_view = 'users.login'


# 创建数据库对象
db = SQLAlchemy()

# 生成jwt_manager
jwt_manager = JWTManager()


# 使用工厂方法创建app对象，方便传不同的配置参数
def create_app(config=None):
    app = Flask(__name__)
    if config is not None:
        # 将配置信息对象记载到app中
        app.config.from_object(config)

    # 注册Blueprint
    from application.common.error_handlers import error
    from application.users.views import users
    from application.home.views import home
    from application.api.users_api import users_api
    from application.api.new_api import new_api
    app.register_blueprint(error, url_prefix='/error')
    app.register_blueprint(users, url_prefix='/users')
    app.register_blueprint(home, url_prefix='/')
    app.register_blueprint(users_api, url_prefix='/api/users')
    app.register_blueprint(new_api, url_prefix='/api/new')

    # 将数据库对象和app关联
    db.init_app(app)
    # jwt关联app
    jwt_manager.init_app(app)
    # login_manager关联app
    login_manager.init_app(app)
    return app
